<script setup>
import axios from "axios";
import { ElMessage } from 'element-plus';
import { onMounted, ref, watch, watchEffect } from "vue";
import { useRouter } from "vue-router";
import MyDatePicker from '../components/MyDatePicker'
import StationSelector from '../components/StationSelector'
import OperaHeader from '../components/OperaHeader'
import IllegalTypeSelector from '../components/IllegalTypeSelector'
import {Plus } from '@element-plus/icons-vue';
import { format } from 'date-fns';

import {download} from '../utils/index'
var role = localStorage.getItem('role')
var isCompany = ref(true)
var lastPage = ref(0)
var time = ref();

const currentRole = ref(localStorage.getItem('role'))


//查看详情信息
const form = ref({
  id: 0,
  pid: 0,
  petrolName: '',
  photo: '',
  illegalType: 0,//1:打手机 2： 3：油罐区检修不规范 4？
  description: '',
  date: '',
  time: '',
})

var tableData = ref([])
// const getBList =()=>{ //总公司全部数据
//   axios.get('/central/getPetrolIllegalBehaviorList?page=1&size=2').then(res=>{
//     tableData.value=res.data.data
//     // // console.log(res.data.data.)
//     // console.log(res.data)
//     // console.log(tableData.value)
//     // console.log(tableData.value.data.pid)
//     // console.log('ttsddf')
//
//   })
// }

const value = ref('All')
const options = [
  {
    value: 'All',
    label: '所有加油站',
  }
]


const router = useRouter()
function renderTime(date) {
  var dateee = new Date(date).toJSON();
  return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

function handleClick(index, row) {
  console.log(row.time);
  sessionStorage.setItem('description', row.remark)
  sessionStorage.setItem('id', row.id)
  sessionStorage.setItem('illegalType', row.basicName)
  sessionStorage.setItem('petrolName', row.deptName)
  sessionStorage.setItem('photo', row.photo)
  sessionStorage.setItem('pid', row.deptId)
  sessionStorage.setItem('dateTime', row.createDate)

  router.push({
    path: '/main/violationDetail',
  })
}
function pList() {
  axios.get('/petrol/getPetrolIllegalBehaviorList?page=' + page.value + '&size=15').then(res => {
    if (res.data.code != 0) ElMessage.error(res.data.msg)
    else {
      tableData.value = res.data.data.data
      lastPage.value = res.data.data.lastPage * 10
      total.value = res.data.data.total
      for (let i = 0; i < total.value; i++) {
        time.value = ref(tableData.value[i].date + " " + tableData.value[i].time)
        tableData.value[i].time = time.value
      }
      console.log(total.value)
      console.log(page.value)
    }
  }).catch(error => {
    console.log('Error', error.message)
  })
}
function cList1() {
  if (value.value == 'All') {
    axios.get('/central/getPetrolIllegalBehaviorList?page=' + page.value + '&size=15').then(res => {
      if (res.data.code != 0) ElMessage.error(res.data.msg)
      else {
        tableData.value = res.data.data.data
        lastPage.value = res.data.data.lastPage * 10
        total.value = res.data.data.total
        for (let i = 0; i < total.value; i++) {
          time.value = ref(tableData.value[i].date + " " + tableData.value[i].time)
          tableData.value[i].time = time.value
        }
      }
    }).catch(error => {
      console.log('Error', error.message)
    })
  } else {
    axios.get('/central/behavior?page=' + page.value + '&size=15' + '&pid=' + value.value).then(res => {
      if (res.data.code != 0) ElMessage.error(res.data.msg)
      else {
        tableData.value = res.data.data.data
        lastPage.value = res.data.data.lastPage * 10
        total.value = res.data.data.total
        for (let i = 0; i < total.value; i++) {
          time.value = ref(tableData.value[i].date + " " + tableData.value[i].time)
          tableData.value[i].time = time.value
        }
      }
    }).catch(error => {
      console.log('Error', error.message)
    })
  }

}
function cList2() {
  if (value.value == 'All') {
    axios.get('/branch/getPetrolIllegalBehaviorList?page=' + page.value + '&size=15').then(res => {
      tableData.value = res.data.data.data
      lastPage.value = res.data.data.lastPage * 10
      total.value = res.data.data.total
      for (let i = 0; i < total.value; i++) {
        time.value = ref(tableData.value[i].date + " " + tableData.value[i].time)
        tableData.value[i].time = time.value
      }

    }).catch(error => {
      console.log('Error', error.message)
    })
  } else {
    axios.get('/branch/behavior?page=' + page.value + '&size=15').then(res => {
      tableData.value = res.data.data.data
      lastPage.value = res.data.data.lastPage * 10
      total.value = res.data.data.total
      for (let i = 0; i < total.value; i++) {
        time.value = ref(tableData.value[i].date + " " + tableData.value[i].time)
        tableData.value[i].time = time.value
      }

    }).catch(error => {
      console.log('Error', error.message)
    })
  }
}

const dateData = ref([])
const pageNum = ref(1)
const total = ref(0)
const pageSize = 15
const staffIds = ref([])
const type = ref([])
const handleSearch = async () => {
  const obj = {
    startDate: dateData.value?.[0],
    endDate: dateData.value?.[1],
    staffIds: staffIds.value,
    pageNum: pageNum.value,
    pageSize,
    type: type.value
  }
  const params = new URLSearchParams(obj).toString()
  const res = await axios.get(`/system/violation?${params}`)
  const {code, msg, ...data} = res.data
  if (code == 200) {
    const {rows, total: tTotal} = data 
    tableData.value = rows
    total.value = tTotal
  } else {
    ElMessage.error(msg)
  }
}

onMounted(() => {
  handleSearch()
  // if (role == 1) {
  //   isCompany.value = true
  //   cList1()
  //   axios.get('/central/petrolList').then(res => {
  //     for (let item in res.data.data.petrolList) {
  //       gridData.push({
  //         'pid': res.data.data.petrolList[item].pid,
  //         'petrolName': res.data.data.petrolList[item].petrolName
  //       })
  //       options.push({
  //         label: res.data.data.petrolList[item].petrolName + '（' + res.data.data.petrolList[item].pid + '）',
  //         value: res.data.data.petrolList[item].pid
  //       })
  //     } console.log(gridData);
  //   })
  // } else if (role == 2) {
  //   isCompany.value = true
  //   axios.get('/branch/petrolList').then(res => {
  //     for (let item in res.data.data.petrolList) {
  //       gridData.push({
  //         'pid': res.data.data.petrolList[item].pid,
  //         'petrolName': res.data.data.petrolList[item].petrolName
  //       })
  //       options.push({
  //         label: res.data.data.petrolList[item].petrolName + '（' + res.data.data.petrolList[item].pid + '）',
  //         value: res.data.data.petrolList[item].pid
  //       })
  //     } console.log(gridData);
  //   })
  //   cList2()
  // } else {//某加油站
  //   isCompany.value = false
  //   pList()
  // }
})
const formatter = (row, column, cellValue) => {
  //return row.illegalType=='1'?'是':'否'
  if (row.illegalType == '1') { return '打手机' } else if (row.illegalType == '2') { return '未正确摆放护栏' } else if (row.illegalType == '3') {
    return '登高未戴安全帽'
  } else if (row.illegalType == '4') {
    return '火灾'
  } else {
    return '卸油区有人'
  }

}


// 导出Excel模块
var exportDataFormVisible = ref(false)
var gridData = []
var exportPid = []
const value1 = ref('')
const handleExportDataRowChange = (val) => {
  exportPid = []
  for (let i in val) {
    exportPid.push(val[i].pid)
  }
  console.log(exportPid);
  // exportPid = currentRow.pid
}
const handleExport = () => {
  exportDataFormVisible.value = false
  console.log(value1.value);

  var exporSiteFile = function () {
    //先判断数据是否填写完整 否则发出提示并退出函数
    if (isCompany.value) {
      if (!value1.value[0] || !value1.value[1] || exportPid.length == 0) {
        ElMessage.error("请确保数据填写完整！")
        return;
      }
    } else {
      if (!value1.value[0] || !value1.value[1]) {
        ElMessage.error("请确保数据填写完整！")
        return;
      }
    }

    let fileId = new Date().getTime(); // 使用当前时间戳作为 fileId
    let params = {
      PCTime: new Date().getTime(),
      RequestType: "File",
      Condition: {
        Action: "SiteParamFile",
        Config: {
          FileID: fileId
        }
      }
    };
    let requestURL = '';
    if (role == 1) requestURL = '/central/exportData' + '?startDate=' + value1.value[0] + '&endDate=' + value1.value[1] + '&pidList=' + exportPid
    else if (role == 2) requestURL = '/branch/exportData' + '?startDate=' + value1.value[0] + '&endDate=' + value1.value[1] + '&pidList=' + exportPid
    else if (role == 3) requestURL = '/petrol/exportData' + '?startDate=' + value1.value[0] + '&endDate=' + value1.value[1]
    axios.get(requestURL, { responseType: 'blob' }).then(res => {
      if (res.data.size > 0) {
        const blob = new Blob([res.data]);
        let url = window.URL.createObjectURL(blob); //根据返回的流文件创建url；url指向流
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        let fileName = decodeURIComponent(res.headers["filename"]);
        link.setAttribute("download", value1.value[0] + 'To' + value1.value[1] + 'By' + exportPid.join('&') + '.xlsx'); // 自定义下载文件名,此处命名为起始时间To结束时间By加油站1&加油站2
        document.body.appendChild(link); //添加不可见a标签
        link.click(); //代码触发a标签的点击事件进行文件下载
      }
    }).catch(error => {
      ElMessage.error(error)
    });
  }
  exporSiteFile()

}

const changeCheckStation = () => {
  console.log(value.value);
  if (role == 1) {
    cList1()
  } else if (role == 2) {
    cList2()
  } else {
    pList()
  }
}

const exportData = async () => {
  try {
    const res = await axios.get('/system/violation/export',{
        responseType: 'arraybuffer'
    })
    download(res.data,res.headers.get('Content-Disposition'))
    ElMessage.success('导出成功')
    
  } catch (err) {
    console.log(err);
    ElMessage.error('操作失败')
  }
}
const addFormValue = ref({})
const addFormVisible = ref(false)
const add = () => {
  console.log('add');
  addFormVisible.value = true
}
function previewImage(file) {
  const url = URL.createObjectURL(file);
 return url
}
const onBeforeUpload = (e) => {
  addFormValue.value.photo = e
  imageUrl.value = previewImage(e)
  console.log(imageUrl.value);
  return false
}
const imageUrl = ref('')
const handleRemove = () => {
  // imageUrl.value = ''
}
const stationSelector = ref(null)
const onAddSubmit = async () => {
  const formData = new FormData()
  formData.append('photo', addFormValue.value.photo)
  formData.append('deptId', addFormValue.value.deptId)
  formData.append('type', addFormValue.value.type)
  formData.append('remark', addFormValue.value.remark)
  formData.append('date', format(addFormValue.value.date, 'yyyy-MM-dd'))
  console.log(formData, addFormValue.value);
  try {
    const res = await axios({
      url: '/system/violation',
      data: formData,
      method: 'post'
    })
    const {msg, code, data} = res.data
    if (code === 200) {
      ElMessage.success('添加成功')
      addFormVisible.value = false
      pageNum.value = 1
      stationSelector.value.reset()
      staffIds.value = []
      type.value = []
      dateData.value = []
      handleSearch()
    } else {
      ElMessage.error(msg)
    }
  } catch (err) {
    ElMessage.error('操作失败')
  }
}
watch(pageNum, () =>{
  handleSearch(pageNum.value)
})
</script>

<template>
  <!--  ！总分公司页面-->
  <div v-if="isCompany">
    <OperaHeader @submit="handleSearch">
      <MyDatePicker v-model="dateData"></MyDatePicker>
      <StationSelector v-model="staffIds" ref="stationSelector" />
      <IllegalTypeSelector v-model="type" />
      <template v-slot:footer>
        <el-button v-if="currentRole==1" round class="exportData" size="large" @click="add" type="primary">添加违规数据</el-button>
        <el-button  class="exportData" @click="exportData" type="primary" size="large"
        round>导出Excel表格</el-button>
      </template>
    </OperaHeader>



    <div class="t_background">
      <div class="tmainBody">
        <el-table stripe :data="tableData" empty-text="暂无违规信息" :header-cell-style="{ 'text-align': 'center' }"
          style="width: 100%">
          <el-table-column prop="createDate" label="时间" align="center" />
          <el-table-column prop="deptId" label="加油站编号" align="center" />
          <el-table-column prop="deptName" label="加油站名称" align="center" />
          <el-table-column prop="basicName" label="违规类型" align="center" />
          <el-table-column prop="remark" label="描述" align="center" />
          <el-table-column prop="links" label="" align="center">
            <template #header>
              <!--              <el-input v-model="search" size="small" placeholder="Type to search" />-->
            </template>
            <template #default="scope">
              <!--              ！！链接-->
              <el-link class="link" @click="handleClick(scope.$index, scope.row)">查看详情</el-link>
            </template>
          </el-table-column>

        </el-table>
        <!--    分页 -->
        <el-row>
          <el-col style="">
            <el-pagination v-model:current-page="pageNum" background hide-on-single-page layout="prev, pager, next" 
              :total="total" :default-page-size="pageSize" />
          </el-col>
        </el-row>
        <!-- 导出excel弹窗 -->
        <!-- <el-dialog v-model="exportDataFormVisible" title="选择加油站导出Excel" width="500">
          <el-date-picker v-model="value1" type="daterange" range-separator="To" start-placeholder="Start date"
            end-placeholder="End date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
          <el-table :data="gridData" @selection-change="handleExportDataRowChange">
            <el-table-column type="index" width="50" />
            <el-table-column type="selection" width="55" />
            <el-table-column property="pid" label="加油站编号" width="150" />
            <el-table-column property="petrolName" label="加油站名字" width="200" />
          </el-table>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="exportDataFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleExport">
                确认导出
              </el-button>
            </div>
          </template>
        </el-dialog> -->
        <el-dialog v-model="addFormVisible" title="添加违规数据" width="500">
          <el-form label-position="right" label-width="auto">
            <el-form-item label="发生时间">
              <el-date-picker v-model="addFormValue.date" />
            </el-form-item>
            <el-form-item label="加油站">
              <StationSelector :multiple="false" v-model="addFormValue.deptId"></StationSelector>
            </el-form-item>
            <el-form-item label="违规类型">
              <IllegalTypeSelector :multiple="false" v-model="addFormValue.type"></IllegalTypeSelector>
            </el-form-item>
            <el-form-item label="描述">
              <el-input type="textarea" v-model="addFormValue.remark"></el-input>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                :before-upload="onBeforeUpload"
                :limit="1"
                :on-remove="handleRemove"
                list-type="picture-card"
              >
                <img style="max-width: 100%; max-height: 100%;" v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                <!-- <svg v-else class="avatar-uploader-icon"  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M480 480V128a32 32 0 0 1 64 0v352h352a32 32 0 1 1 0 64H544v352a32 32 0 1 1-64 0V544H128a32 32 0 0 1 0-64z"></path></svg> -->
              </el-upload>
            </el-form-item>
             <el-form-item>
              <div style="display: flex;justify-content:  flex-end;width: 100%;">
                
                <el-button @click="() => addFormVisible= false">取消</el-button>
                <el-button type="primary" @click="onAddSubmit">确定</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-dialog>


      </div>
    </div>
  </div>

  <!--  某加油站页面-->

</template>

<style scoped>
#topBox {
  padding: 0 5%;
  margin-top: 2%;
  display: flex;
  justify-content: space-between;
}

.el-table__header-wrapper,
.el-table__body-wrapper,
.el-table__footer-wrapper {
  width: fit-content;
  margin: auto;
}

.stasionExportData {
  margin-top: 2%;
  margin-left: 5%;
}

.exportData {
  width: fit-content;
  display: block;
}

.link {
  color: var(--el-color-primary);
  text-decoration: underline !important;
}

.t_background {
  width: 90%;
  background-color: #ffffff;
  margin: auto;
}

.tmainBody {
  width: 90%;
  margin: 2% auto 0;
  /*justify-content: center;*/
  /*margin: auto;*/
}

.el-pagination {
  margin: 10px auto;
  width: fit-content;
}

.tmainBody>>>.el-table__row>td {
  /* 去除表格线 */
  border: none;
}

/*.tmainBody >>> .el-table th.is-leaf {*/
/*  !* 去除上边框 *!*/
/*  border: none;*/
/*}*/
.el-table--fit.el-table--striped.el-table--enable-row-hover.el-table--enable-row-transition.el-table.el-table--layout-fixed.is-scrolling-none {
  margin: 20px 0;
}
</style>